package com.shxc.smarttrade.account.activity;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.just.library.AgentWeb;
import com.just.library.ChromeClientCallbackManager;
import com.shxc.smarttrade.MyApplication;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.account.adapter.CustomerPagerAdapter;
import com.shxc.smarttrade.base.BaseActivity;
import com.shxc.smarttrade.info.Contents;
import com.shxc.smarttrade.main.MainActivity;
import com.shxc.smarttrade.old.bean.ChartRoomInfo;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.utils.Loger;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.shxc.smarttrade.utils.ToastUtils;

import org.xchris.view.annotation.ContentView;
import org.xchris.view.annotation.Event;
import org.xchris.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.CSCustomServiceInfo;
import io.rong.imlib.model.UserInfo;
import okhttp3.Call;

/**
 * 帮助中心
 */
@ContentView(R.layout.activity_helpcenter)
public class HelpCenterActivity extends BaseActivity implements View.OnClickListener {

    @ViewInject(R.id.title_textview)
    TextView title_textview;
    @ViewInject(R.id.left_imageview)
    ImageView left_imageview;
    @ViewInject(R.id.linearlayout)
    LinearLayout linearlayout;
    @ViewInject(R.id.viewpager)
    ViewPager viewpager;
    @ViewInject(R.id.point_linearlayout)
    LinearLayout point_linearlayout;

    private AgentWeb mAgentWeb;

    private boolean isOperate = false;
    private CustomerPagerAdapter adapter;
    // 底部小点图片
    private ImageView[] dots;
    // 记录当前选中位置
    private int currentIndex;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        title_textview.setText("客服中心");
        left_imageview.setVisibility(View.VISIBLE);

        getConversationToken();

        mAgentWeb = AgentWeb.with(this)//传入Activity
                .setAgentWebParent(linearlayout, new LinearLayout.LayoutParams(-1, -1))//传入AgentWeb 的父控件 ，如果父控件为 RelativeLayout ， 那么第二参数需要传入 RelativeLayout.LayoutParams
                .useDefaultIndicator()// 使用默认进度条
                .setIndicatorColor(Color.parseColor("#38385D"))
                .setReceivedTitleCallback(mCallback) //setting Web 页面的 title 回调
                .createAgentWeb()//
                .ready()
                .go(Contents.HELP_H5);

        List<Integer> list = new ArrayList<>();
        list.add(R.mipmap.popup_service_1);
        list.add(R.mipmap.popup_service_2);
        list.add(R.mipmap.popup_service_3);

        initDots();

        point_linearlayout.setVisibility(View.GONE);

        adapter = new CustomerPagerAdapter(LayoutInflater.from(mContext), mContext, list, handler);
        viewpager.setAdapter(adapter);
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                // 设置底部小点选中状态
                setCurDot(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @Event({R.id.left_imageview, R.id.call_view, R.id.call_imageview})
    private void onClickk(View view) {

        switch (view.getId()) {
            case R.id.left_imageview:
                //关闭
                if (!isOperate) {
                    if (mAgentWeb.getWebCreator().get().canGoBack()) {
                        mAgentWeb.getWebCreator().get().goBack();
                    } else {
                        finish();
                    }
                }
                break;
            case R.id.call_view:
            case R.id.call_imageview:
                //客服
//                ToastUtils.showToast("客服系统即将上线，敬请期待");
//                isOperate = true;
//                viewpager.setVisibility(View.VISIBLE);
//                point_linearlayout.setVisibility(View.VISIBLE);
                if (spImp.getUserId() == -1 || SpUtils.getInt(mContext, "userId", -1) == -1) {
                    ToastUtils.showToast("请先登录");
                } else {
                    CSCustomServiceInfo.Builder csBuilder = new CSCustomServiceInfo.Builder();
                    CSCustomServiceInfo csInfo = csBuilder.nickName("客服").build();
                    String customerServiceId = SpUtils.getString(mContext, "customerServiceId");
                    if (!TextUtils.isEmpty(customerServiceId)) {
                        RongIM.getInstance().startCustomerServiceChat(mContext, customerServiceId, "客服", csInfo);
                    } else {
                        ToastUtils.showToast("初始化失败,请重试");
                    }
                }

                break;
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (!isOperate) {
                    if (mAgentWeb.getWebCreator().get().canGoBack()) {
                        mAgentWeb.getWebCreator().get().goBack();
                        return true;
                    } else {
                        finish();
                    }
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    protected ChromeClientCallbackManager.ReceivedTitleCallback mCallback = new ChromeClientCallbackManager.ReceivedTitleCallback() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (title_textview != null && !TextUtils.isEmpty(title))
                if (title.length() > 10)
                    title = title.substring(0, 10).concat("...");
            title_textview.setText(title);

            Message msg = new Message();
            msg.obj = title;
            msg.what = 1;
            handler.sendMessage(msg);
        }
    };

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String title = (String) msg.obj;
//                    if (!title.equals("帮助中心")) {
//                        right_imageview.setVisibility(View.GONE);
//                    } else {
//                        right_imageview.setVisibility(View.VISIBLE);
//                    }
                    break;
                case 2:
                    //关闭
                    isOperate = false;
                    viewpager.setVisibility(View.GONE);
                    point_linearlayout.setVisibility(View.GONE);
                    viewpager.setCurrentItem(0);
                    break;
                case 3:
                    //客服入口
//                    ToastUtils.showToast("客服即将上线。");
//                    isOperate = false;
//                    viewpager.setVisibility(View.GONE);
//                    point_linearlayout.setVisibility(View.GONE);
//                    viewpager.setCurrentItem(0);

                    int position = (int) msg.obj;
                    Loger.e("position", position);

                    if (SpUtils.getInt(mContext, "userId", -1) == -1) {
                        ToastUtils.showToast("请先登录");
                    } else {
                        CSCustomServiceInfo.Builder csBuilder = new CSCustomServiceInfo.Builder();
                        CSCustomServiceInfo csInfo = csBuilder.nickName("客服").build();
                        String customerServiceId = SpUtils.getString(mContext, "customerServiceId");
                        if (!TextUtils.isEmpty(customerServiceId)) {
                            RongIM.getInstance().startCustomerServiceChat(mContext, customerServiceId, "客服", csInfo);
                        } else {
                            ToastUtils.showToast("初始化失败,请重试");
                        }
                    }

                    break;
            }
            super.dispatchMessage(msg);
        }
    };


    private void initDots() {
        dots = new ImageView[3];

        // 循环取得小点图片
        for (int i = 0; i < 3; i++) {
            // 得到一个LinearLayout下面的每一个子元素
            dots[i] = (ImageView) point_linearlayout.getChildAt(i);
            dots[i].setEnabled(false);// 都设为灰色
            dots[i].setOnClickListener(this);
            dots[i].setTag(i);// 设置位置tag，方便取出与当前位置对应
        }

        currentIndex = 0;
        dots[currentIndex].setEnabled(true); // 设置为白色，即选中状态
    }


    @Override
    public void onClick(View v) {
        int position = (Integer) v.getTag();
        setCurView(position);
        setCurDot(position);
    }

    /**
     * 设置当前view
     *
     * @param position
     */
    private void setCurView(int position) {
        if (position < 0 || position >= 3) {
            return;
        }
        viewpager.setCurrentItem(position);
    }

    /**
     * 设置当前指示点
     *
     * @param position
     */
    private void setCurDot(int position) {
        if (position < 0 || position > 3 || currentIndex == position) {
            return;
        }
        dots[position].setEnabled(true);
        dots[currentIndex].setEnabled(false);
        currentIndex = position;
    }

    /**
     * 获取聊天基本信息
     */
    private void getConversationToken() {
        if (spImp.getUserId() == -1) return;
        Loger.e("getConversationToken", "ssssssss");
        Map<String, Object> map = new HashMap<>();
        map.put("userId", spImp.getUserId());
        MyOkHttpUtils.getServiceDatas(this, map, URLContents.MAINACTIVITY_CHARTROOM_GETTOKEN, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                ToastUtils.showToast("网络异常");
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    Gson gsom = new Gson();
                    ChartRoomInfo ci = gsom.fromJson(response, ChartRoomInfo.class);
                    if (ci.getErr_code().equals("0")) {
                        ChartRoomInfo.DataBeanX.DataBean cdb = ci.getData().getData();
                        SpUtils.putString(HelpCenterActivity.this, "chartRoomId", cdb.getChatroomId());
                        SpUtils.putString(HelpCenterActivity.this, "customerServiceId", cdb.getCustomerServiceId());
                        Loger.e("token", cdb.getToken());
                        connect(cdb.getToken(), cdb.getUserId(), cdb.getUserName(), cdb.getUserPortrait());
                    } else
                        ToastUtils.showToast(ci.getErr_msg());
                }

            }
        });
    }

    /**
     * <p>连接服务器，在整个应用程序全局，只需要调用一次，需在 init 之后调用。</p>
     * <p>如果调用此接口遇到连接失败，SDK 会自动启动重连机制进行最多10次重连，分别是1, 2, 4, 8, 16, 32, 64, 128, 256, 512秒后。
     * 在这之后如果仍没有连接成功，还会在当检测到设备网络状态变化时再次进行重连。</p>
     *
     * @param token 从服务端获取的用户身份令牌（Token）。
     * @return RongIM  客户端核心类的实例。
     */
    private void connect(String token, final String id, final String name, final String headUrl) {
        RongIM.getInstance().disconnect();
//        if (TextUtils.isEmpty(rongimtoken)) return;
        if (getApplicationInfo().packageName.equals(MyApplication.getCurProcessName(getApplicationContext()))) {

            RongIM.connect(token, new RongIMClient.ConnectCallback() {

                /**
                 * Token 错误。可以从下面两点检查 1.  Token 是否过期，如果过期您需要向 App Server 重新请求一个新的 Token
                 *                  2.  token 对应的 appKey 和工程里设置的 appKey 是否一致
                 */
                @Override
                public void onTokenIncorrect() {
                    Loger.e("onTokenIncorrect", "...");
                }

                /**
                 * 连接融云成功
                 * @param userid 当前 token 对应的用户 id
                 */
                @Override
                public void onSuccess(String userid) {
                    Loger.e("userId-success", userid);
                    RongIM.getInstance().setCurrentUserInfo(new UserInfo(id, name, Uri.parse(headUrl)));
                    RongIM.getInstance().setMessageAttachedUserInfo(true);
                }

                /**
                 * 连接融云失败
                 * @param errorCode 错误码，可到官网 查看错误码对应的注释
                 */
                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                    Loger.e("errCode:", errorCode.getMessage());
                }
            });
        }
    }
}
